package cn.zhz.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil2 {

    private static final ThreadLocal sessionTL = new ThreadLocal();
    private static Configuration configuration;
    private final static SessionFactory sessionFactory;
    static {
        try {
            configuration = new Configuration().configure();
            sessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session currentSession() {
        Session session = (Session) sessionTL.get();
        if (session == null) {
            session = sessionFactory.openSession();
            sessionTL.set(session);
        }
        return session;
    }

    public static void closeSession(){
        Session session = (Session) sessionTL.get();
        sessionTL.set(null);
        session.close();
    }
}
